package com.形为型模式.观察者模式;

import java.util.ArrayList;
import java.util.EventListener;
import java.util.EventObject;
import java.util.List;

/**
 * 铃声事件
 *
 */
class RingEvent extends EventObject{
   boolean sound;
   RingEvent(Object source,boolean sound){
       super(source);
       this.sound = sound;

   }

    public boolean isSound() {
        return sound;
    }

    public void setSound(boolean sound) {
        this.sound = sound;
    }
}
/**
 * 抽象事件监听器 抽象观察者
 */
interface BellEventListener extends EventListener{
    void headBell(RingEvent e);
}
/**
 * 老师事件监听器
 */
class TeachEventListener implements BellEventListener{
    @Override
    public void headBell(RingEvent e) {
        if(e.sound){
            System.out.print("上课铃响了");
            System.out.println("老师上课了");
        }else{
            System.out.print("下课铃响了");
            System.out.println("老师下课了");
        }
    }

}
/**
 * 学生事件监听器
 */
class StuEventListener implements BellEventListener{
    @Override
    public void headBell(RingEvent e) {
       if(e.sound){
           System.out.print("上课铃响了");
           System.out.println("同学们上课了");
       }
       else{
           System.out.print("下课铃响了");
           System.out.println("同学们下课了");
       }
    }
}

/**
 * 铃声事件源 观察者目标类
 */
class BellEventSoruce{
    List<BellEventListener> listener;
    BellEventSoruce(){
        listener = new ArrayList<>();
    }
    void addPersonListener(BellEventListener ren){
        listener.add(ren);
    }
    void ring(boolean sound){
        String type = sound?"上课铃":"下课铃";
        System.out.println(type+"响");
        RingEvent event = new RingEvent(this,sound);
        notifies(event);
    }
    void notifies(RingEvent e){
        for(Object o:listener){
            ((BellEventListener)o).headBell(e);
        }
    }

}
/**
 * 观察者模式 之 学校的上下课铃声
 */
public class ObserveMusic {
    public static void main(String[] args) {
      BellEventSoruce bell = new BellEventSoruce();
      bell.addPersonListener(new TeachEventListener());
      bell.addPersonListener(new StuEventListener());
      bell.ring(true);
      bell.ring(false);


    }
}
